﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Windows.System;
using Microsoft.Devices.Sensors;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using zhangkong.ViewModels;
using Color = System.Windows.Media.Color;

namespace zhangkong
{
    public partial class CoursePage : PhoneApplicationPage
    {
        private string postdata;
        private string postback;



        private static bool IsCourseLoaded = false;

        private ApplicationBarMenuItem settingsMenuItem;
        private ApplicationBarMenuItem leadingInCourseMenuItem;
        private ApplicationBarMenuItem aboutMenuItem;
        private ApplicationBarMenuItem logOffMenuItem;

        public static SolidColorBrush[] CourseColorBrush = new SolidColorBrush[12];

        public static int ColorNum = 0;

        private static WeeklyCourses weeklyCourses;

        private Grid courseGrid;//奇怪这里为什么改成了static之后导航到下一个页面时课程会消失？？？？

        private static int currentPage = 0;

        private static int tempraryWeekNumber;


        PeriodicTask periodicTask;

        string periodicTaskName = "PeriodicAgent";


        public static WeeklyCourses MyWeeklyCourses
        {
            get
            {
                if (weeklyCourses != null)
                    return weeklyCourses;
                string dataFromIsoStore;
                if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("ParsedWeek" + (App.WeekNumber - 1).ToString(), out dataFromIsoStore))
                {
                    weeklyCourses = JsonConvert.DeserializeObject<WeeklyCourses>(dataFromIsoStore);
                    return weeklyCourses;
                }
                else
                {
                    MessageBox.Show("从独立存储中加载数据失败……请重新导入课表");
                    return null;
                }
            }
        }

        public CoursePage()
        {

            InitializeColor();

            #region 初始化颜色值
            try
            {
                ColorNum = Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["ColorNum"]);
            }
            catch (Exception)
            {

            }
            #endregion

            InitializeComponent();

            //DataContext = MyWeeklyCourses;

            this.BackKeyPress += CoursePage_BackKeyPress;


            #region 初始化应用程序栏
            ApplicationBar = new ApplicationBar();
            ApplicationBar.Opacity = 0.7;
            ApplicationBar.Mode = ApplicationBarMode.Minimized;
            ApplicationBar.ForegroundColor = Colors.White;
            ApplicationBar.BackgroundColor = Colors.Transparent;


            settingsMenuItem = new ApplicationBarMenuItem("设置");
            settingsMenuItem.Click += settingsMenuItem_Click;
            leadingInCourseMenuItem = new ApplicationBarMenuItem("常见问题");
            leadingInCourseMenuItem.Click += leadingInCourseMenuItem_Click;
            aboutMenuItem = new ApplicationBarMenuItem("关于");
            aboutMenuItem.Click += aboutMenuItem_Click;
            logOffMenuItem = new ApplicationBarMenuItem("注销");
            logOffMenuItem.Click += logOffMenuItem_Click;

            ApplicationBar.MenuItems.Add(settingsMenuItem);
            ApplicationBar.MenuItems.Add(leadingInCourseMenuItem);
            ApplicationBar.MenuItems.Add(aboutMenuItem);
            ApplicationBar.MenuItems.Add(logOffMenuItem);
            ApplicationBar.StateChanged += ApplicationBar_StateChanged;

            #endregion


            this.Loaded += CoursePage_Loaded;
        }

        #region Background Schedule Agent
        void CoursePage_Loaded(object sender, RoutedEventArgs e)
        {
            int version = 0;
            if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("version", out version))
            {
            }
            if (version < App.version)
            {
                MessageBox.Show(" 1.修复切换前景色后颜色显示不正确的BUG\n 2.修复切换周数后再次返回页面没有显示本周的BUG\n 3.修复闪退的BUG","更新说明", MessageBoxButton.OKCancel);
            }
            IsolatedStorageSettings.ApplicationSettings["version"] = App.version;

            RefreshTiles();

            StartPeriodicAgent();
        }

        private void RefreshTiles()
        {
            if(App.IsCourseImported == false)
                return;
            TimeSpan t1 = new TimeSpan(new DateTime(2014, 9, 1).Ticks);
            TimeSpan t2 = new TimeSpan(DateTime.Now.Ticks);

            TimeSpan offset = t2.Subtract(t1);//计算天数之差

            int weekNumber = offset.Days / 7;//计算周数

            string dataFromIsoStore =
                Convert.ToString(IsolatedStorageSettings.ApplicationSettings["ParsedWeek" + weekNumber.ToString()]);

            WeeklyCourses weeklyCourses = new WeeklyCourses();
            weeklyCourses = JsonConvert.DeserializeObject<WeeklyCourses>(dataFromIsoStore);

            int dayofweek = ((int)DateTime.Now.DayOfWeek - 1 + 7) % 7;
            DailyCourses dailyCourses = weeklyCourses.WeeklyCoursesCollention[dayofweek];


            bool latestCourse = true;
            ShellTile TileToFind = ShellTile.ActiveTiles.First();
            IconicTileData data = new IconicTileData();

            data.Title = "掌控校园";
            data.Count = 0;
            data.IconImage = new Uri("/toolargemiddle.png", UriKind.Relative);
            data.SmallIconImage = new Uri("/toolargesmall.png", UriKind.Relative);
            data.WideContent1 = "";
            data.WideContent2 = "";
            data.WideContent3 = "";


            int count = 0;
            for (int i = 0; i < dailyCourses.DailyCoursesCollection.Count; i++)
            {
                Course course = dailyCourses.DailyCoursesCollection[i];
                if (course.CourseName != "")
                {
                    if (DateTime.Now < course.StartTime.AddMinutes(20)) //保证在上课20分钟内不会更新磁贴
                    {
                        count++;
                        if (latestCourse)
                        {
                            data.IconImage = new Uri("/toolargemiddle.png", UriKind.Relative);
                            data.SmallIconImage = new Uri("/toolargesmall.png", UriKind.Relative);
                            data.WideContent1 = course.CourseName;
                            data.WideContent2 = "时间：" + course.StartTime.ToShortTimeString() + "--" +
                                                course.EndTime.ToShortTimeString();
                            data.WideContent3 = "地点：" + course.Classroom;
                            latestCourse = false;
                        }

                    }

                }

            }

            data.Count = count;
            TileToFind.Update(data);

        }

        private void StartPeriodicAgent()
        {
            if (App.IsCourseImported == false) 
                return;

            if (App.DynamicTile == false)
            {
                RemoveAgent(periodicTaskName);
                return;
            }


            // Obtain a reference to the period task, if one exists
            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule
            if (periodicTask != null)
            {
                return;
                RemoveAgent(periodicTaskName);
            }

            periodicTask = new PeriodicTask(periodicTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            periodicTask.Description = "This demonstrates a periodic task.";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(periodicTask);

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if(DEBUG_AGENT)
            ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(10));
#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                }

                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.

                }
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
            }
        }


        private void RemoveAgent(string name)
        {

            try
            {
                ScheduledActionService.Remove(name);
            }
            catch (Exception)
            {
            }
        }
        #endregion

        void logOffMenuItem_Click(object sender, EventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("注销会清空本地记录，是否继续？", "确认注销", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                IsolatedStorageSettings.ApplicationSettings.Remove("StudentID");
                IsolatedStorageSettings.ApplicationSettings.Remove("PassWord");
                IsolatedStorageSettings.ApplicationSettings.Remove("RemPassword");
                string password;
                if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("ID", out password))
                {
                    IsolatedStorageSettings.ApplicationSettings.Remove("ID");
                }
                else if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("StudentPassword", out password))
                {
                    IsolatedStorageSettings.ApplicationSettings.Remove("StudentPassword");
                }

                IsolatedStorageSettings.ApplicationSettings["IsCourseImported"] = false;
                App.IsCourseImported = false;
                IsCourseLoaded = false;
                IsolatedStorageSettings.ApplicationSettings.Save();
                NavigationService.Navigate(new Uri("/SignInPage.xaml?logOff=true", UriKind.Relative));
            }

        }

        void ApplicationBar_StateChanged(object sender, ApplicationBarStateChangedEventArgs e)
        {
            if (ApplicationBar.BackgroundColor == Colors.Transparent)
                ApplicationBar.BackgroundColor = Colors.Black;
            else
                ApplicationBar.BackgroundColor = Colors.Transparent;

        }

        void aboutMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
        }

        void leadingInCourseMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/HelpPage.xaml", UriKind.Relative));
        }

        void settingsMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/CoursePageSettings.xaml", UriKind.Relative));
        }

        void CoursePage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (DetailCanvas.Visibility == Visibility.Visible)
            {
                DetailCanvas.Visibility = Visibility.Collapsed;
                e.Cancel = true;
            }
        }

        private void InitializeColor()//初始化颜色值
        {
            CourseColorBrush[0] = new SolidColorBrush(Color.FromArgb((byte)110, (byte)31, (byte)182, (byte)110));
            CourseColorBrush[1] = new SolidColorBrush(Color.FromArgb((byte)110, (byte)7, (byte)189, (byte)230));
            CourseColorBrush[2] = new SolidColorBrush(Color.FromArgb((byte)110, (byte)222, (byte)16, (byte)16));
            CourseColorBrush[3] = new SolidColorBrush(Color.FromArgb((byte)110, (byte)16, (byte)36, (byte)166));
            CourseColorBrush[4] = new SolidColorBrush(Color.FromArgb((byte)110, (byte)194, (byte)17, (byte)83));
            CourseColorBrush[5] = new SolidColorBrush(Color.FromArgb((byte)110, (byte)68, (byte)21, (byte)122));
            CourseColorBrush[6] = new SolidColorBrush(Color.FromArgb((byte)110, (byte)224, (byte)30, (byte)92));
            CourseColorBrush[7] = new SolidColorBrush(Color.FromArgb((byte)110, (byte)116, (byte)0, (byte)255));
            CourseColorBrush[8] = new SolidColorBrush(Color.FromArgb((byte)110, (byte)190, (byte)199, (byte)15));
            CourseColorBrush[9] = new SolidColorBrush(Color.FromArgb((byte)110, (byte)216, (byte)12, (byte)198));
            CourseColorBrush[10] = new SolidColorBrush(Color.FromArgb((byte)110, (byte)0, (byte)122, (byte)204));
            CourseColorBrush[11] = new SolidColorBrush(Color.FromArgb((byte)110, (byte)15, (byte)192, (byte)60));
        }

        private void ShowDetailofCourse_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            int i = Convert.ToInt32(btn.Tag.ToString()[0]) - 48;
            int j = Convert.ToInt32(btn.Tag.ToString()[1]) - 48;


            Course myCourse = MyWeeklyCourses.WeeklyCoursesCollention[i].DailyCoursesCollection[j];
            if (String.IsNullOrEmpty(myCourse.CourseName))
                return;

            CourseNameTextBlock.Text = myCourse.CourseName;
            ClassroomTextBlock.Text = myCourse.Classroom;
            TeacherNameTextBlock.Text = myCourse.TeacherName;
            ClassHoursTextBlock.Text = myCourse.ClassHours;
            CreditsTextBlock.Text = myCourse.Credits;

            DetailofCourseGrid.Background = btn.Background;
            DetailCanvas.Visibility = Visibility.Visible;
        }


        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            ApplicationBar.BackgroundColor = Colors.Transparent;

            int index = MyPivot.SelectedIndex;
            if (index == 0)
                CourseScrollViewer0.Content = null;
            else if (index == 1)
                CourseScrollViewer1.Content = null;
            else
                CourseScrollViewer2.Content = null;
            if (App.WhetherChangeColor)//如果用户关闭了自动更改颜色，那么就不保存颜色状态
                IsolatedStorageSettings.ApplicationSettings["ColorNum"] = ColorNum;//保存上一次的ColorNum用于每次打开时颜色都不同
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            LoadBackgroundImage();

            IDictionary<string, string> queryString = NavigationContext.QueryString;
            if (queryString.ContainsKey("start"))
            {
                while (NavigationService.CanGoBack)
                {
                    NavigationService.RemoveBackEntry();
                }
            }
            
            //判断本地是否导入了课表
            if (App.IsCourseImported == false)
            {
                LeadingInCanvas.Visibility = Visibility.Visible;//导入课表
                return;
            }


            CaculateCourseNumber();

            
            InitializeCourseGrid();


        }

        private void CaculateCourseNumber()
        {

            int offset = 0;

            DateTime time = new DateTime(2014, 9, 1);
            while (time.Date != DateTime.Now.Date)
            {
                offset++;
                time = time.AddDays(1);
            }


            App.WeekNumber = offset / 7;//计算周数

            IsolatedStorageSettings.ApplicationSettings["WeekNumber"] = App.WeekNumber;

            WeekNumberTextBlock.Text = "第" + (App.WeekNumber + 1).ToString() + "周";
            CurrentWeekTextBlock.Visibility = Visibility.Visible;
            tempraryWeekNumber = App.WeekNumber;

        }
        private void LoadBackgroundImage()
        {
            try
            {
                BitmapImage img = new BitmapImage();
                string filePath = App.BackgroundImageUri;
                using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (iso.FileExists(filePath))
                    {
                        using (var source = iso.OpenFile(filePath, FileMode.Open, FileAccess.Read))
                        {
                            img.SetSource(source);
                        }
                        ImageBrush imgBrush = new ImageBrush();
                        imgBrush.ImageSource = img;
                        LayoutRoot.Background = imgBrush;
                    }
                    else
                    {
                        MessageBox.Show("亲，没能找到背景图片！请卸载后重新安装应用！");
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\nError In\nCoursePgae.xaml\n反馈有奖");
            }

        }
        private void ClosePopup_Click(object sender, RoutedEventArgs e)
        {
            DetailCanvas.Visibility = Visibility.Collapsed;

        }
        private void LeadingIn_Click(object sender, RoutedEventArgs e)
        {
            string id = Convert.ToString(IsolatedStorageSettings.ApplicationSettings["StudentID"]);
            string password = null;
            if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("ID", out password))
            {

            }
            else if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("StudentPassword", out password))
            {

            }

            else
            {
                PasswordCanvas.Visibility = System.Windows.Visibility.Visible;
                PasswordTextBox.Focus();
                return;
            }


            //postdata = "uname=201313030114&upwd=chengjing";
            postdata = "uname=" + id + "&upwd=" + password;
            string uri = "http://202.115.137.129/zhangkong/curl.php";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.BeginGetRequestStream(StreamCallback, httpWebRequest);

            LeadingInButton.IsEnabled = false;
            ProgressBar.Visibility = Visibility.Visible;
        }
        private void ConfirmButton_CLick(object sender, RoutedEventArgs e)
        {
            IsolatedStorageSettings.ApplicationSettings["StudentPassword"] = PasswordTextBox.Text;
            IsolatedStorageSettings.ApplicationSettings.Save();
            PasswordCanvas.Visibility = Visibility.Collapsed;



            string id = Convert.ToString(IsolatedStorageSettings.ApplicationSettings["StudentID"]);
            string password = null;
            if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("ID", out password))
            {

            }
            else if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("StudentPassword", out password))
            {

            }

            else
            {
                PasswordCanvas.Visibility = Visibility.Visible;
                PasswordTextBox.Focus();
                return;
            }

            //postdata = "uname=201313030114&upwd=chengjing";
            postdata = "uname=" + id + "&upwd=" + password;
            string uri = "http://202.115.137.129/zhangkong/curl.php";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.BeginGetRequestStream(StreamCallback, httpWebRequest);

            ProgressBar.Visibility = Visibility.Visible;

        }

        #region
        //下面进行回调函数
        ///////////////////
        private void StreamCallback(IAsyncResult result)
        {

            HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
            using (Stream stream = httpWebRequest.EndGetRequestStream(result))
            {
                byte[] entryBytes = Encoding.UTF8.GetBytes(postdata);
                stream.Write(entryBytes, 0, entryBytes.Length);
            }

            //这里就和上面GET方法获得回复回调一样，用 private void ResponseCallback(IAsyncResult result) 这个方法。
            httpWebRequest.BeginGetResponse(ResponseCallback, httpWebRequest);
        }
        //第二个回调函数
        private void ResponseCallback(IAsyncResult result)
        {
            Stream stream = null;

            try
            {
                //获取异步操作返回的的信息 
                HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
                //结束对 Internet 资源的异步请求
                WebResponse webResponse = httpWebRequest.EndGetResponse(result);
                stream = webResponse.GetResponseStream();
                using (StreamReader sr = new StreamReader(stream))
                {
                    postback = sr.ReadToEnd();
                }
            }
            catch 
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("未能连接到远程服务器，请检查本地网络!", "程序异常", MessageBoxButton.OK);
                    ProgressBar.Visibility = Visibility.Collapsed;

                });
                return;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }




            if (postback != "")
            {
                IsolatedStorageSettings.ApplicationSettings["postback"] = postback;
                IsolatedStorageSettings.ApplicationSettings.Save();

                //因为HttpWebRequest是异步，不在UI线程上。所以要改变UI线程上的控件属性就要用Dispatcher.BeginInvoke()。  
                Dispatcher.BeginInvoke(() =>
                {
                    try
                    {//提示：必须先切割字符串
                        //postback = "{\"day1\":{\"1\":{\"coursename\":\"\\u62a5\\u5230\\u6ce8\\u518c\",\"classroom\":null,\"xueshi\":null,\"xuefen\":null,\"lilun\":null,\"teacher\":null}}}";
                        //MessageBox.Show(postback.Length.ToString());
                        string[] allCourseData = postback.Split(new char[] { '&' }); //做字符串分割 s[0]表示第一串字符

                        //把最原始的信息存入独立存储
                        for (int i = 0; i < allCourseData.Length; i++)
                        {
                            IsolatedStorageSettings.ApplicationSettings["Week" + i.ToString()] = allCourseData[i];
                        }
                        IsolatedStorageSettings.ApplicationSettings["TermLength"] = allCourseData.Length;
                        IsolatedStorageSettings.ApplicationSettings.Save();


                        string[] startTimeofCourse = new string[]
                        {
                            "8:10:0", "9:0:0", "10:15:0", "11:05:0", "12:40:0", "14:30", "15:20:0", "16:15:0", "17:05:0",
                            "19:10:0", "20:0:0", "20:50:0"
                        };

                        string[] endTimeofCourse = new[]
                        {
                            "8:55:0", "9:45:0", "11:0:0", "11:50:0", "14:0:0", "15:15:0", "16:05:0", "17:0:0", "17:50",
                            "19:55:0", "20:45:0", "21:35:0"
                        };


                        DateTime startTime = new DateTime(2014,9,1);

                        for (int k = 0; k < allCourseData.Length; k++)
                        {
                            string weeklyCourseData = allCourseData[k];
                            if (weeklyCourseData == "")
                                continue;

                            JObject jsonData = JObject.Parse(weeklyCourseData);

                            WeeklyCourses weekly = new WeeklyCourses();
                            weekly.StartTime = startTime;
                            weekly.Number = k + 1;
                            for (int i = 0; i < 7; i++)
                            {
                                DailyCourses daily = new DailyCourses();


                                for (int j = 0; j < 12; )
                                {
                                    bool whetherIgnore = false;//是否跳过中午那节课，用于课程结束时间的判断

                                    Course course = new Course();

                                    course.CourseName = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["coursename"].ToString();
                                    if (course.CourseName == "教研" || course.CourseName == "中秋节" ||
                                        course.CourseName == "国庆节" || course.CourseName == "报到注册" ||
                                        course.CourseName == "考试周" || course.CourseName == "元旦节")
                                        course.CourseName = "";

                                    course.Classroom = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["classroom"].ToString();
                                    course.CourseType = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["lilun"].ToString();
                                    course.Credits = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["xuefen"].ToString();
                                    course.ClassHours = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["xueshi"].ToString();
                                    course.TeacherName = jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][(j + 1).ToString()]["teacher"].ToString();
                                    course.StartTime =
                                        DateTime.Parse(startTime.Year + "/" + startTime.Month + "/" + startTime.Day +
                                                       " " + startTimeofCourse[j]);

                                    int length = 1;
                                    //循环查询下一节课是否和本节相同
                                    while (j + length < 12 && course.CourseName ==
                                           jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][
                                               (j + 1 + length).ToString()]["coursename"].ToString()
                                               && course.Classroom == jsonData[(i + 1).ToString()]["day" + (i + 1).ToString()][
                                               (j + 1 + length).ToString()]["classroom"].ToString()
                                               )
                                    {
                                        length++;
                                        if (length + j == 4 && App.MaximumCourseNumber == 11) //跳过中午那节课
                                        {
                                            j++;
                                            whetherIgnore = true;
                                        }
                                    }

                                    j += length;
                                    if (whetherIgnore)
                                        course.EndTime =
                                            DateTime.Parse(startTime.Year + "/" + startTime.Month + "/" + startTime.Day +
                                                           " " + endTimeofCourse[j - 2]);
                                    else
                                        course.EndTime =
                                            DateTime.Parse(startTime.Year + "/" + startTime.Month + "/" + startTime.Day +
                                                           " " + endTimeofCourse[j - 1]);

                                    course.Length = length;
                                    daily.DailyCoursesCollection.Add(course);
                                }
                                startTime = startTime.AddDays(1);
                                weekly.WeeklyCoursesCollention.Add(daily);
                            }
                            var dataofWeeks = JsonConvert.SerializeObject(weekly);
                            IsolatedStorageSettings.ApplicationSettings["ParsedWeek" + k.ToString()] = dataofWeeks;
                        }

                        App.IsCourseImported = true;
                        IsolatedStorageSettings.ApplicationSettings["IsCourseImported"] = App.IsCourseImported;
                        IsolatedStorageSettings.ApplicationSettings.Save();
                        LeadingInCanvas.Visibility = Visibility.Collapsed;
                        ProgressBar.Visibility = Visibility.Collapsed;

                        CaculateCourseNumber();

                        InitializeCourseGrid();

                        RefreshTiles();
                        StartPeriodicAgent();

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                });
            }
            else
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("密码错误，请重新输入密码！");
                    PasswordCanvas.Visibility = System.Windows.Visibility.Visible;
                    ProgressBar.Visibility = Visibility.Collapsed;
                    PasswordTextBox.Focus();
                });
                
                
                //MessageBox.Show("课表服务器崩溃了！！！\n我们正在鞭打程序员……");
            }

        }

        #endregion


        private void InitializeCourseGrid()
        {
            courseGrid = new Grid();
            courseGrid.Loaded += courseGrid_Loaded;

            for (int i = 0; i < App.MaximumCourseNumber + 1; i++)//加一是为了在底部留出空隙
            {
                RowDefinition rowDefinition = new RowDefinition();
                GridLength height = new GridLength(61.42);
                rowDefinition.Height = height;
                courseGrid.RowDefinitions.Add(rowDefinition);
            }

            ColumnDefinition columnDefinition1 = new ColumnDefinition();//左侧写课程数
            GridLength width1 = new GridLength(50);
            columnDefinition1.Width = width1;
            courseGrid.ColumnDefinitions.Add(columnDefinition1);

            for (int i = 0; i < 7; i++)
            {
                ColumnDefinition columnDefinition = new ColumnDefinition();
                GridLength width = new GridLength(61.42);
                columnDefinition.Width = width;
                courseGrid.ColumnDefinitions.Add(columnDefinition);
            }


            int index = MyPivot.SelectedIndex;
            if (index == 0)
                CourseScrollViewer0.Content = courseGrid;
            else if (index == 1)
                CourseScrollViewer1.Content = courseGrid;
            else
                CourseScrollViewer2.Content = courseGrid;



            DateTime time = (new DateTime(2014, 9, 1)).AddDays(tempraryWeekNumber*7);

            string[] week = new string[] {"一", "二", "三", "四", "五", "六", "日"};

            MonthTextBlock.Text = time.Month.ToString() + "\n月";

            MondayTextBlock.Text = time.Day.ToString() + "\n周一";
            if (time.Date == DateTime.Now.Date)
                MondayTextBlock.Opacity = 1;
            else
                MondayTextBlock.Opacity = 0.5;
            time = time.AddDays(1);


            TuesdayTextBlock.Text = time.Day.ToString() + "\n周二";
            if (time.Date == DateTime.Now.Date)
                TuesdayTextBlock.Opacity = 1;
            else
                TuesdayTextBlock.Opacity = 0.5;
            time = time.AddDays(1);


            WednesdayTextBlock.Text = time.Day.ToString() + "\n周三";
            if (time.Date == DateTime.Now.Date)
                WednesdayTextBlock.Opacity = 1;
            else
                WednesdayTextBlock.Opacity = 0.5;
            time = time.AddDays(1);


            ThursdayTextBlock.Text = time.Day.ToString() + "\n周四";
            if (time.Date == DateTime.Now.Date)
                ThursdayTextBlock.Opacity = 1;
            else
                ThursdayTextBlock.Opacity = 0.5;
            time = time.AddDays(1);


            FridayTextBlock.Text = time.Day.ToString() + "\n周五";
            if (time.Date == DateTime.Now.Date)
                FridayTextBlock.Opacity = 1;
            else
                FridayTextBlock.Opacity = 0.5;
            time = time.AddDays(1);


            SaturdayTextBlock.Text = time.Day.ToString() + "\n周六";
            if (time.Date == DateTime.Now.Date)
                SaturdayTextBlock.Opacity = 1;
            else
                SaturdayTextBlock.Opacity = 0.5;
            time = time.AddDays(1);


            SundayTextBlock.Text = time.Day.ToString() + "\n周日";
            if (time.Date == DateTime.Now.Date)
                SundayTextBlock.Opacity = 1;
            else
                SundayTextBlock.Opacity = 0.5;


        }

        void courseGrid_Loaded(object sender, RoutedEventArgs e)
        {
            LoadCourseFromIsoStore();
        }
        private void LoadCourseFromIsoStore()
        {
            int i = 0, k = 0;//i控制最大课程的数量，k控制课程编号

            for (; i < 4; i++, k++) 
            {
                TextBlock textBlock = new TextBlock();
                textBlock.Text = (k + 1).ToString();
                textBlock.TextAlignment = TextAlignment.Center;
                textBlock.VerticalAlignment = VerticalAlignment.Center;
                SolidColorBrush brush = new SolidColorBrush(Color.FromArgb((byte)200, (byte)255, (byte)255, (byte)255));
                textBlock.Foreground = brush;
                FontSize = 20;
                textBlock.FontFamily = new FontFamily("Microsoft YaHei");
                Grid.SetRow(textBlock, i);
                Grid.SetColumn(textBlock, 0);
                courseGrid.Children.Add(textBlock);
            }

            if (App.MaximumCourseNumber == 12)
            {
                TextBlock textBlock = new TextBlock();
                textBlock.Text = "午";
                textBlock.TextAlignment = TextAlignment.Center;
                textBlock.VerticalAlignment = VerticalAlignment.Center;
                SolidColorBrush brush = new SolidColorBrush(Color.FromArgb((byte)200, (byte)255, (byte)255, (byte)255));
                textBlock.Foreground = brush;
                FontSize = 20;
                textBlock.FontFamily = new FontFamily("Microsoft YaHei");
                Grid.SetRow(textBlock, 4);
                Grid.SetColumn(textBlock, 0);
                courseGrid.Children.Add(textBlock);
                i++;
            }

            for (; i < App.MaximumCourseNumber; i++, k++) 
            {
                TextBlock textBlock = new TextBlock();
                textBlock.Text = (k + 1).ToString();
                textBlock.TextAlignment = TextAlignment.Center;
                textBlock.VerticalAlignment = VerticalAlignment.Center;
                SolidColorBrush brush = new SolidColorBrush(Color.FromArgb((byte)200, (byte)255, (byte)255, (byte)255));
                textBlock.Foreground = brush;
                FontSize = 20;
                textBlock.FontFamily = new FontFamily("Microsoft YaHei");
                Grid.SetRow(textBlock, i);
                Grid.SetColumn(textBlock, 0);
                courseGrid.Children.Add(textBlock);
            }


            string dataFromIsoStore =
                Convert.ToString(IsolatedStorageSettings.ApplicationSettings["ParsedWeek" + tempraryWeekNumber.ToString()]);

            weeklyCourses = JsonConvert.DeserializeObject<WeeklyCourses>(dataFromIsoStore);

            i = 0;
            for (; i < MyWeeklyCourses.WeeklyCoursesCollention.Count; i++)
            {
                int temp = 0;

                for (int j = 0; j < MyWeeklyCourses.WeeklyCoursesCollention[i].DailyCoursesCollection.Count; j++)
                {
                    Course course = MyWeeklyCourses.WeeklyCoursesCollention[i].DailyCoursesCollection[j];

                    if (String.IsNullOrEmpty(course.CourseName))
                    {
                        temp += course.Length;
                        continue;
                    }
                    Button button = new Button();
                    button.Opacity = 0.9;
                    button.Style = this.Resources["CourseButton"] as Style;
                    button.Background = CourseColorBrush[ColorNum];
                    //button.Background = new SolidColorBrush(Color.FromArgb((byte)50, (byte)255, (byte)255, (byte)255));
                    button.Tag = i.ToString() + j.ToString();
                    button.Click += ShowDetailofCourse_Click;
                    button.Margin = new Thickness(1, 1, 1, 1);
                    button.Content = course.Detail;


                    Grid.SetRow(button, temp);
                    Grid.SetColumn(button, i + 1);
                    Grid.SetRowSpan(button, course.Length);
                    courseGrid.Children.Add(button);
                    temp += course.Length;

                    ColorNum++;
                    if (ColorNum >= 12)
                        ColorNum = 0;
                }

            }
            IsCourseLoaded = true;
        }
        private void ChangeWeekView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (IsCourseLoaded == false)
                return;

            int newPage = MyPivot.SelectedIndex;
            if ((currentPage == 0 && newPage == 2) || (currentPage == 1 && newPage == 0) ||
                (currentPage == 2 && newPage == 1))
            {
                //App.WeekNumber--
                tempraryWeekNumber--;
                if (tempraryWeekNumber == -1)
                    tempraryWeekNumber = 20;
                WeekNumberTextBlock.Text = "第" + (tempraryWeekNumber + 1).ToString() + "周";

                if (tempraryWeekNumber == Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["WeekNumber"]))
                    CurrentWeekTextBlock.Visibility = Visibility.Visible;
                else
                    CurrentWeekTextBlock.Visibility = Visibility.Collapsed;

                InitializeCourseGrid();
                //courseGrid.Children.Clear();
                //LoadCourseFromIsoStore();


                if (newPage == 0)
                {
                    CourseScrollViewer1.Content = null;
                    CourseScrollViewer0.Content = courseGrid;
                }
                else if (newPage == 1)
                {
                    CourseScrollViewer0.Content = null;
                    CourseScrollViewer2.Content = null;
                    CourseScrollViewer1.Content = courseGrid;
                }
                else
                {
                    CourseScrollViewer0.Content = null;
                    CourseScrollViewer2.Content = courseGrid;
                }

                currentPage = newPage;
            }
            else
            {
                //App.WeekNamber++
                tempraryWeekNumber++;
                if (tempraryWeekNumber == 21)
                    tempraryWeekNumber = 0;


                WeekNumberTextBlock.Text = "第" + (tempraryWeekNumber + 1).ToString() + "周";

                if (tempraryWeekNumber == Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["WeekNumber"]))
                    CurrentWeekTextBlock.Visibility = Visibility.Visible;
                else
                    CurrentWeekTextBlock.Visibility = Visibility.Collapsed;

                //courseGrid.Children.Clear();
                //LoadCourseFromIsoStore();
                InitializeCourseGrid();

                if (newPage == 0)
                {
                    CourseScrollViewer2.Content = null;
                    CourseScrollViewer0.Content = courseGrid;
                }

                else if (newPage == 1)
                {
                    CourseScrollViewer0.Content = null;
                    CourseScrollViewer1.Content = courseGrid;

                }
                else
                {
                    CourseScrollViewer0.Content = null;
                    CourseScrollViewer1.Content = null;
                    CourseScrollViewer2.Content = courseGrid;
                }

                currentPage = newPage;

            }

        }

    }
}